import React from "react";
import { getMoodPostDetail, getPostThumbNum, getPostCommentNum } from "@/api/moodPostController";
import { Card, Avatar, Tag, Divider } from "antd";
import { EyeOutlined, LikeOutlined, MessageOutlined, ShareAltOutlined } from "@ant-design/icons";
import Image from "next/image";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import "dayjs/locale/zh-cn";
import UserInfoCard from "@/components/UserInfoCard";
import Link from "next/link";
import { cookies } from "next/headers";
import { headers } from 'next/headers';

dayjs.extend(relativeTime);
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.locale("zh-cn");

// 心情状态映射
const moodStateMap = [
  "开心", "兴奋", "平静", "轻松", "满足", "无聊", "困倦", "气炸", "暴怒", "难过",
  "沮丧", "郁闷", "焦虑", "烦躁", "疲惫", "失落", "无助", "委屈", "烦恼", "崩溃"
];

// 配置页面选项
export const dynamic = "force-dynamic";
export const fetchCache = 'force-no-store';
export const revalidate = 0;

export default async function MoodPostDetailPage({ params }: { params: { id: string } }) {
  const postId = parseInt(params.id);
  let post: any = null;
  let thumbNum = 0;
  let commentNum = 0;
  
  try {
    const cookieStore = cookies();
    const headersList = headers();
    const timestamp = Date.now();
    
    const requestHeaders = {
      "Content-Type": "application/json",
      Cookie: cookieStore.toString(),
      "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0",
      Pragma: "no-cache",
      Expires: "-1",
      "X-Request-Time": timestamp.toString(),
      "X-User-Session": cookieStore.toString(),
    };

    // 获取帖子详情
    const postResponse = await fetch(
      `http://localhost:3000/api/rice/mood/detail?postId=${postId}&t=${timestamp}`,
      {
        method: "POST",
        headers: requestHeaders,
        cache: "no-store",
        next: { 
          revalidate: 0,
          tags: ['mood-detail']
        },
        credentials: "include",
        body: JSON.stringify({
          postId,
          _t: timestamp
        }),
      },
    );
    
    const postRes = await postResponse.json();
    if (postRes?.code === 0 && postRes?.data) {
      post = Array.isArray(postRes.data) && postRes.data.length > 0 ? postRes.data[0] : postRes.data;
    }
    
    // 获取点赞数和评论数
    if (post) {
      const [thumbRes, commentRes] = await Promise.all([
        fetch(
          `http://localhost:3000/api/rice/mood/thumb/count?postId=${postId}&t=${timestamp}`,
          {
            method: "POST",
            headers: requestHeaders,
            cache: "no-store",
            next: { revalidate: 0 },
            credentials: "include",
            body: JSON.stringify({ postId, _t: timestamp }),
          }
        ),
        fetch(
          `http://localhost:3000/api/rice/mood/comment/count?postId=${postId}&t=${timestamp}`,
          {
            method: "POST",
            headers: requestHeaders,
            cache: "no-store",
            next: { revalidate: 0 },
            credentials: "include",
            body: JSON.stringify({ postId, _t: timestamp }),
          }
        )
      ]);
      
      const thumbData = await thumbRes.json();
      const commentData = await commentRes.json();
      
      thumbNum = thumbData?.data || 0;
      commentNum = commentData?.data || 0;
    }
  } catch (error) {
    console.error("Failed to fetch post detail:", error);
  }

  const formatTime = (time: string) => {
    return dayjs.utc(time).tz("Asia/Shanghai").fromNow();
  };

  const getWorkStatus = (isWork: number) => {
    switch (isWork) {
      case 0:
        return "上班";
      case 1:
        return "学习";
      case 2:
        return "休息";
      default:
        return "未知";
    }
  };

  if (!post) {
    return (
      <div style={{ 
        maxWidth: 800, 
        margin: '0 auto', 
        padding: '20px',
        display: 'flex',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <Link href="/mood" style={{ marginBottom: 16, display: 'block' }}>
          ← 返回心情列表
        </Link>
        <Card>
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            帖子不存在或已被删除
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div style={{ 
      maxWidth: 800, 
      margin: '0 auto', 
      padding: '20px',
      display: 'flex',
      flexDirection: 'column',
      gap: '16px'
    }}>
      <Link href="/mood" style={{ marginBottom: 16, display: 'block' }}>
        ← 返回心情列表
      </Link>
      
      <Card
        style={{
          width: "100%",
          borderRadius: "8px",
          boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
        }}
        bodyStyle={{
          padding: "22px",
        }}
      >
        <div style={{ display: "flex", marginBottom: 12 }}>
          <div
            style={{
              width: 48,
              height: 48,
              borderRadius: 50,
              overflow: "hidden",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              background: "#fff",
            }}
          >
            <img
              src={post.userAvatar}
              alt="avatar"
              width={48}
              height={48}
              style={{
                width: "48px",
                height: "48px",
                borderRadius: "50%",
              }}
            />
          </div>
          <div
            style={{
              marginLeft: 8,
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
              gap: 4
            }}
          >
            <div
              style={{
                fontSize: "15px",
                fontWeight: 500,
                color: "#262626",
              }}
            >
              {post.remarks || post.userName}
            </div>
            <div
              style={{
                marginTop: 0,
                color: "#595959",
                fontSize: 13,
              }}
            >
              {post.direction} @{post.userName} · {formatTime(post.createTime)}
            </div>
          </div>
        </div>

        <div style={{ marginBottom: 12 }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {/* 工作状态标签 */}
            <Tag style={{
              backgroundColor: '#f7f8fa',
              color: '#888',
              border: '1px solid #e5e6eb',
              borderRadius: 16,
              padding: '4px 12px',
              fontSize: 14,
            }}>
              {getWorkStatus(post.isWork)}
            </Tag>
            {/* 起床时间标签 */}
            <Tag style={{
              backgroundColor: '#f7f8fa',
              color: '#888',
              border: '1px solid #e5e6eb',
              borderRadius: 16,
              padding: '4px 12px',
              fontSize: 14,
            }}>
              {post.earlyTime?.split("T")[1].slice(0, 5)} 起床
            </Tag>
            {/* 预计晚休时间标签 */}
            <Tag style={{
              backgroundColor: '#f7f8fa',
              color: '#888',
              border: '1px solid #e5e6eb',
              borderRadius: 16,
              padding: '4px 12px',
              fontSize: 14,
            }}>
              {post.eveningTime?.split("T")[1].slice(0, 5)} 晚休
            </Tag>
            {/* 心情状态标签 */}
            {post.moodState !== undefined && post.moodState >= 0 && post.moodState < moodStateMap.length && (
              <Tag
                style={{
                  backgroundColor: '#f7f8fa',
                  color: '#1677FF',
                  borderRadius: 16,
                  padding: '4px 12px',
                  fontSize: 12,
                  border: 'none',
                  display: 'inline-block',
                  lineHeight: '18px',
                  height: 'auto',
                }}
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <div style={{ width: 18, height: 18, borderRadius: '50%', background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <img src="/assets/moostate.svg" alt="mood state icon" style={{ width: 12, height: 12 }} />
                  </div>
                  <span>{moodStateMap[post.moodState]}</span>
                </div>
              </Tag>
            )}
          </div>
        </div>

        <div
          style={{
            marginBottom: 12,
            fontSize: 15,
            lineHeight: 1.6,
            color: "#262626",
            whiteSpace: "pre-line",
          }}
        >
          {post.content}
        </div>

        {post.photoName && (
          <div style={{ marginBottom: 12, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            {post.photoName.split(',').map((url: string, idx: number) => (
              <div key={idx} style={{ position: 'relative', maxWidth: '100%' }}>
                <img
                  src={url}
                  alt={`心情图片${idx + 1}`}
                  style={{ 
                    maxWidth: '100%', 
                    maxHeight: 500,
                    objectFit: 'contain',
                    borderRadius: 8 
                  }}
                />
              </div>
            ))}
          </div>
        )}

        <Divider style={{ margin: '16px 0' }} />

        {/* 底部操作按钮 */}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            width: "100%",
            padding: "0 30px 0px 30px",
            background: "#fff"
          }}
        >
          <div style={{ display: "flex", alignItems: "center", flex: 1, justifyContent: "flex-start" }}>
            <button
              style={{
                color: "#222",
                fontWeight: 500,
                fontSize: 14,
                display: "flex",
                alignItems: "center",
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                padding: '8px 12px',
              }}
            >
              <ShareAltOutlined style={{ fontSize: 14, marginRight: 4 }} />
              分享
            </button>
          </div>
          <div style={{ display: "flex", alignItems: "center", flex: 1, justifyContent: "center" }}>
            <button
              style={{
                color: "#222",
                fontWeight: 500,
                fontSize: 14,
                display: "flex",
                alignItems: "center",
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                padding: '8px 12px',
              }}
            >
              <MessageOutlined style={{ fontSize: 14, marginRight: 4 }} />
              {commentNum > 0 ? commentNum : "评论"}
            </button>
          </div>
          <div style={{ display: "flex", alignItems: "center", flex: 1, justifyContent: "flex-end" }}>
            <button
              style={{
                color: "#222",
                fontWeight: 500,
                fontSize: 14,
                display: "flex",
                alignItems: "center",
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                padding: '8px 12px',
              }}
            >
              <LikeOutlined style={{ fontSize: 15, marginRight: 4 }} />
              {thumbNum > 0 ? thumbNum : "点赞"}
            </button>
          </div>
        </div>
      </Card>
      
      <div style={{ marginTop: 16 }}>
        <UserInfoCard />
      </div>
    </div>
  );
} 